#include "decaptcher.hxx"
#include <util.hxx>

string Decaptcher::DecDomain = "http://www.fasttypers.org/imagepost.ashx";
//string Decaptcher::DecDomain = "http://www.fasttypers.org/ImagePost_debug.ashx";

string Decaptcher::Key = "16W1Z9G5SRCTXRK4RUDC9YNJXXDXPD1KZF96PZ9G";

static bool registered = DecaptcherFactory::Instance()->RegisterDecaptcher(ExpertdeCoders, Decaptcher::Instance());

Decaptcher* Decaptcher::Instance(void)
{
	static Mutex mutex;
	static Decaptcher* _instance = 0;

	if (_instance == NULL)
	{
		Util::Lock lock(&mutex);
		if (_instance == NULL)
		{
			_instance = new Decaptcher();
		}
	}
	
	return _instance;
}

/* return  genId OK
 * return 0 - something failed
 */
int Decaptcher::Decode(char* image, int inLen, string& result)
{
	static long genCounter = 0;

	CURL* curl = Util::NewSrvCURL();

	string escapedStr = Util::EscapeStr(image);

	int genId = Util::GetAGenId();

	////////////////////////////////////////////////////////////
	// http://expertdecoders.com/download-api-plugin/
	//////////////////////////////////////////
	char* dataFields = new char[escapedStr.length() + 200];
	sprintf_s(dataFields, escapedStr.length() + 200, "action=upload&key=%s&gen_task_id=%d&file=%s", Key.c_str(), genId, escapedStr.c_str());

	int ret = 0;
	stringstream ssresult;
	if (0 == (ret = Util::PerformStepInternal(curl, DecDomain, dataFields, ssresult)))
	{
		result = ssresult.str();

		ret = genId;
	}

	delete[] dataFields;

	Util::CleanupCurl(curl);

	return ret;
}

/////////////////////////////////////////////////////////
// Return 0 OK, or 
// error No.
// 1:Error UNKNOWN
int Decaptcher::Refund(int genId, string& errmsg)
{
	CURL* curl = Util::NewSrvCURL();

	////////////////////////////////////////////////////////////
	// http://expertdecoders.com/download-api-plugin/
	//////////////////////////////////////////
	char dataFields[200];
	sprintf_s(dataFields, 200, "action=refund&key=%s&gen_task_id=%d", Key.c_str(), genId);

	int res = -1;
	stringstream ssresult;
	if (0 == (res = Util::PerformStepInternal(curl, DecDomain, dataFields, ssresult)))
	{
		if (!Util::FileContain(ssresult, "ok"))
		{
			errmsg = ssresult.str();
			res = -1;
		}
	}

	Util::CleanupCurl(curl);

	return res;
}